/**
 * 存储适配器工厂
 * 简化版本，只支持核心适配器
 */

import { IStorageAdapter, IStorageConfig } from './interfaces';
import { BrowserStorageAdapter } from './BrowserStorageAdapter';
import { OSSStorageAdapter } from './OSSStorageAdapter';

/**
 * 存储适配器工厂
 */
export class StorageAdapterFactory {
  private static instance: StorageAdapterFactory;

  private constructor() {}

  /**
   * 获取单例实例
   */
  static getInstance(): StorageAdapterFactory {
    if (!StorageAdapterFactory.instance) {
      StorageAdapterFactory.instance = new StorageAdapterFactory();
    }
    return StorageAdapterFactory.instance;
  }

  /**
   * 创建存储适配器
   * @param type 适配器类型，默认自动检测
   * @param config 配置选项
   */
  create(type?: string, config?: IStorageConfig): IStorageAdapter {
    const adapterType = type || this.detectAdapterType();
    
    switch (adapterType) {
      case 'browser':
        return new BrowserStorageAdapter(config);
      
      case 'oss':
        return new OSSStorageAdapter(config);
      
      default:
        throw new Error(`Unsupported storage adapter type: ${adapterType}`);
    }
  }

  /**
   * 创建并初始化存储适配器
   * @param type 适配器类型
   * @param config 配置选项
   */
  async createAndInitialize(type?: string, config?: IStorageConfig): Promise<IStorageAdapter> {
    const adapter = this.create(type, config);
    await adapter.initialize(config);
    return adapter;
  }

  /**
   * 获取支持的适配器类型
   */
  getSupportedTypes(): string[] {
    return ['browser', 'oss'];
  }

  /**
   * 检测环境并推荐适配器类型
   */
  getRecommendedType(): string {
    return this.detectAdapterType();
  }

  /**
   * 自动检测适配器类型
   */
  private detectAdapterType(): string {
    // 检测浏览器环境
    if (typeof window !== 'undefined' && typeof indexedDB !== 'undefined') {
      return 'browser';
    }
    
    // 检测 Node.js 环境
    if (typeof process !== 'undefined' && process.versions && process.versions.node) {
      return 'oss'; // Node.js 环境默认使用 OSS
    }
    
    // 默认使用浏览器存储
    return 'browser';
  }
}

// 导出单例实例
export const storageAdapterFactory = StorageAdapterFactory.getInstance();

/**
 * 便捷函数：创建存储适配器
 */
export function createStorageAdapter(type?: string, config?: IStorageConfig): IStorageAdapter {
  return storageAdapterFactory.create(type, config);
}

/**
 * 便捷函数：创建并初始化存储适配器
 */
export function createAndInitializeStorageAdapter(type?: string, config?: IStorageConfig): Promise<IStorageAdapter> {
  return storageAdapterFactory.createAndInitialize(type, config);
}
